<template>
  <!-- 对账单管理-->
  <el-container>
    <el-header>
      <div class="left-panel">
        <!-- <el-button
          type="primary"
          icon="el-icon-plus"
          @click="returnMoney"
        ></el-button> -->
      </div>
      <div class="right-panel">
        <div class="right-panel-search">
          <!-- <el-select
            v-model="searchValue.customerId"
            placeholder="请选择客户"
            style="width: 100%"
            remote
            filterable
            remote-show-suffix
            :remote-method="queryCustomer"
            :loading="selectCustomerLoading"
            clearable
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            />
          </el-select> -->
          <sc-table-select
            style="width: 100%"
            v-model="searchSelect.customer"
            :apiObj="apiObjCustomer"
            :table-width="700"
            clearable
            collapse-tags
            collapse-tags-tooltip
            :props="props"
            :params="customerForm"
            @change="changeCustomer"
          >
            <template #header="{ form, submit }">
              <el-form :model="customerForm">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input
                      v-model="customerForm.name"
                      placeholder="客户名称"
                      clearable
                      style="width: 100%"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerForm.startTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="开始时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerForm.endTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="结束时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item width="100%">
                      <el-button type="primary" @click="submit">查询</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </template>
            <el-table-column
              prop="customerName"
              label="客户名称"
              min-width="150"
            ></el-table-column>
            <el-table-column
              prop="numbers"
              label="合同成交量"
              min-width="150"
            ></el-table-column>
          </sc-table-select>
          <el-select
            v-model="searchValue.customerAdminId"
            placeholder="请选择业客户创建人"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="searchValue.isFinish"
            placeholder="请选择回款状态"
            style="width: 100%"
            clearable
          >
            <el-option label="未完成" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
          <el-date-picker
            v-model="searchValue.time"
            type="month"
            placeholder="选择账期时间"
            value-format="YYYY-MM"
            style="width: 100%"
          ></el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="upsearch"
          ></el-button>
        </div>
      </div>
    </el-header>
    <!-- <div class="count" v-auths="['financeCount']">
      <p>应收金额：{{ money.planTotal ?? 0 }}元</p>
      <p>实收金额：{{ money.paymentTotal ?? 0 }}元</p>
    </div> -->
    <el-main class="nopadding">
      <scTable
        ref="table"
        row-key="id"
        :apiObj="apiObj"
        :params="searchValue"
        @row-dblclick="handleRowDblclick"
        :showSummary="true"
        :summary-method="getSummaries"
      >
        <el-table-column
          label="ID"
          prop="id"
          width="80"
          fixed
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="客户名称"
          prop="customerName"
          min-width="200"
          :show-overflow-tooltip="true"
          fixed
        ></el-table-column>
        <el-table-column label="账期" width="250" :show-overflow-tooltip="true">
          <template #default="scope">
            <p>{{ scope.row.startTime }}--{{ scope.row.endTime }}的账单</p>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="累计应收"
          prop="accruedPlanMoney"
          width="150"
        ></el-table-column>
        <el-table-column
          label="累计实收"
          prop="accruedPaymentMoney"
          width="150"
        ></el-table-column>
        <el-table-column
          label="总欠款"
          prop="totalMoney"
          width="150"
        >
        <template #default="scope">
            <p>{{ scope.row.accruedPlanMoney-scope.row.accruedPaymentMoney}}元</p>
        </template>
        </el-table-column> -->
        <el-table-column
          label="本期应收"
          prop="planMoney"
          width="100"
        ></el-table-column>
        <el-table-column label="本期实收(抹零)" prop="" width="150">
          <template #default="scope">
            <p>
              {{ scope.row.paymentMoney
              }}<span> ({{ scope.row.balanceMoney }})</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="本期欠款" prop="balanceMoney" width="100">
          <template #default="scope">
            <p>
              {{
                scope.row.planMoney -
                scope.row.paymentMoney -
                scope.row.balanceMoney
              }}
            </p>
          </template>
        </el-table-column>
        <!-- <el-table-column label="抹零金额" prop="balancingMoney" width="100">
          <template #default="scope">
            <p>{{ scope.row.balanceMoney }}元</p>
          </template>
        </el-table-column> -->
        <el-table-column label="状态" prop="" width="100" fixed="right">
          <template #default="scope">
            <p v-if="scope.row.isFinish === 0" style="color: #ad1025">未完成</p>
            <p v-if="scope.row.isFinish === 1" style="color: #398ee5">已完成</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="right" width="300">
          <template #default="scope">
            <el-button-group>
              <el-button
                text
                type="primary"
                size="small"
                @click="table_show(scope.row, scope.$index)"
                v-auth-button="['show/bill']"
                >查看</el-button
              >
              <el-button
                text
                type="primary"
                size="small"
                @click="table_returnList(scope.row, scope.$index)"
                v-auth-button="['show/bill']"
                >收款明细</el-button
              >
              <el-button
                text
                type="primary"
                size="small"
                @click="table_export(scope.row, scope.$index)"
                v-auth-button="['show/bill']"
                >导出</el-button
              >
              <el-button
                v-if="scope.row.isFinish == 0"
                text
                type="primary"
                size="small"
                @click="table_returnMoney(scope.row, scope.$index)"
                v-auth-button="['returnMoney/bill']"
                >收款</el-button
              >
              <el-popconfirm
                title="确定更新吗？"
                @confirm="table_update(scope.row, scope.$index)"
              >
                <template #reference>
                  <el-button
                    text
                    type="primary"
                    size="small"
                    v-auth-button="['update/bill']"
                    >更新</el-button
                  >
                </template>
              </el-popconfirm>
            </el-button-group>
          </template>
        </el-table-column>
      </scTable>
    </el-main>
  </el-container>

  <return-money-dialog
    v-if="dialog.returnMoney"
    ref="returnMoney"
    @success="handleSaveSuccess"
    @closed="dialog.returnMoney = false"
  ></return-money-dialog>
  <return-list-dialog ref="returnList"></return-list-dialog>
</template>

<script>
import returnMoneyDialog from './components/returnMoney'
import returnListDialog from '../components/returnList'
import { exportFile } from '@/utils/exportFile'
export default {
  name: 'bill',
  components: {
    returnMoneyDialog,
    returnListDialog
  },
  data () {
    return {
      dialog: {
        returnMoney: false,
      },
      apiObj: this.$API.finance.bill.getBillList,
      apiObjCustomer: this.$API.finance.plancollect.getCustomerNumbers,
      searchValue: {
        search: null,
        customerName: null,
        customerAdminId: null,//客户创建人
        planStatus: null,
        startTime: null,
        endTime: null,
        customerId: null,
      },
      searchSelect: {},
      customerForm: {
        name: null,
        startTime: null,
        endTime: null,
      },
      props: {
        label: "customerName",
        value: "id",
      },
      searchValue: {
        customerId: null,
        customerAdminId: null,
        isFinish: null,
        time: null
      },
      selectCustomerLoading: false,
      customerList: [],
      // columnsFilters: ['accruedPlanMoney','accruedPaymentMoney','planMoney','paymentMoney'],
      columnsFilters: ['balanceMoney', 'planMoney', 'paymentMoney'],
      money: {},
      userList: [],
    }
  },
  mounted () {
    this.getCustomerList()
    this.getCount()
    this.getUserList()
  },
  methods: {
    //收款
    table_returnMoney (row) {
      this.dialog.returnMoney = true
      this.$nextTick(() => {
        this.$refs.returnMoney.open(row)
      })
    },
    //合计行统计
    getSummaries (param) {

      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "页合计"
          return
        }
        // console.log(sums[3])

        if (this.columnsFilters.includes(column.property)) {
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              console.log(prev, curr)
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += " 元"

          } else {
            sums[index] = ""
          }
        }
      })
      return sums
    },
    // 导出
    async table_export (row) {
      let res = await this.$API.finance.bill.exportBillById.get({ id: row.id })
      console.log(res)
      exportFile(res, '账单明细.xls')
    },
    //编辑
    table_edit (row) {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open('edit').setData(row)
      })
    },
    //查看
    table_show (row) {
      this.$router.push({
        path: '/finance/bill/billDetail',
        query: {
          id: row.id
        }
      })
    },
    // 收款明细
    async table_returnList (row) {
      let api = this.$API.finance.bill.returnList
      this.$refs.returnList.open(row, api, 2)
    },
    // 更新
    async table_update (row) {
      var res = await this.$API.finance.bill.update.post({ billId: row.id })
      if (res.code == 200) {
        this.$refs.table.refresh()
        this.$message.success("更新成功")
      }
    },

    // 获取统计金额
    async getCount () {
      let { data } = await this.$API.finance.bill.getBillCount.get({ customerId: this.searchValue.customerId })
      this.money = data
    },

    // 获取客户列表
    async getCustomerList (val) {
      this.selectCustomerLoading = true
      let param = {
        limit: 1000,
        page: 1,
        search: val,
        //settlement: 2//结算方式 1现结 2月结
      }
      let res = await this.$API.customer.getCustomers.get(param)
      this.selectCustomerLoading = false
      this.customerList = res.data
    },

    // 搜索客户
    queryCustomer (val) {
      this.getCustomerList(val)
    },
    changeCustomer (val) {
      this.searchValue.customerId = val.id
    },

    // 获取所有用户列表
    async getUserList () {
      let data = {
        limit: 1000,
        page: 1,
      }
      let res = await this.$API.user.getUserList.get(data)
      this.userList = res.data
    },
    //搜索
    upsearch () {
      this.$refs.table.upData(this.searchValue)
      this.getCount()

    },
    //本地更新数据
    handleSaveSuccess () {
      this.$refs.table.refresh()

    },
    // 双击表格
    handleRowDblclick (row) {
      this.table_show(row)
    }

  }
}
</script>

<style lang='scss' scoped>
.count {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 50px;
  padding-left: 12px;
  font-size: 14px;
  color: #555;
  font-weight: 600;
  p {
    margin-right: 20px;
  }
}
</style>
